import {
  validUsername
} from '@/utils/validate'

export default {
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的帐号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        callback()
      }
    }
    return {
      loginForm: {
        logName: 'gyez_t1',
        logPws: 'a123456'
      },
      loginRules: {
        logName: [{
          required: true,
          trigger: 'blur',
          validator: validateUsername
        }],
        logPws: [{
          required: true,
          trigger: 'blur',
          validator: validatePassword
        }]
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined
    }
  },
  created() {
    // if (this.$route.query.ACCESS_TOKEN) {

    // } else {

    // }

    // window.location.href = process.env.VUE_APP_BASE_API + '/login'
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      // window.location.href = process.env.VUE_APP_BASE_API + '/login'
      const _this = this
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // console.log(valid)
          this.loading = true
          this.$store.dispatch('user/loginToken', this.loginForm).then((response) => {
            /* console.log(response) */
            const router = {
              path: '/'
            }
            // console.log(router)
            _this.$router.push(router) // 路由跳转
            _this.loading = false
          }).catch((err) => {
            console.log(err)
            _this.loading = false
          })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    handleLogin1() {
      // window.location.href = process.env.VUE_APP_BASE_API + '/login'
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm).then((res) => {
            // console.log('res')
            // this.$router.push({
            //   path: this.redirect || '/'
            // })
            this.loading = true
          }).catch(() => {
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
